package com.seven.webhook.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledFuture;

/**
 * 这是个定时任务启动类，在springboot启动完成后，先查询数据库，发现数据库中的定时备份记录
 * 并自动创建与之对应的定时任务，并将保存到map中。如果做修改直接找到map中的任务进行修改即可
 */
@Configuration
@Component
public class ScheduledFutureComponent {
    private static ConcurrentMap<String,ScheduledFuture> map=new ConcurrentHashMap<String,ScheduledFuture>();
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    @Bean
    public ThreadPoolTaskScheduler trPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    /**
     * 创建定时任务
     * 如果存在定时任务，修改定时任务时间
     */
    public void create(String id, CronTrigger cronTrigger,Runnable runnable){
        ScheduledFuture scheduledFuture = map.get(id);
        if (scheduledFuture!=null){
            end(id);
            create(id,cronTrigger,runnable);
        }else {
            scheduledFuture = threadPoolTaskScheduler.schedule(runnable, cronTrigger);
            map.put(id,scheduledFuture);
        }
    }
    /**
     * 结束定时任务
     */
    public void end(String id){
        ScheduledFuture scheduledFuture = map.get(id);
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
            map.remove(id);
        }
    }
}
